package com.alarm.ecp;

import com.alarm.ecp.constant.EventConstant;
import com.alarm.ecp.pojo.EventPO;
import com.alarm.ecp.utils.KafkaUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.io.IOException;

/**
 * 检测最近1分钟内【连续】登录失败超过3次的用户
 * 基于【个体模式】
 * CEP模式：3次登录失败事件必须是连续的【严格紧邻】
 * 添加该方法即可.consecutive()
 */
public class LoginFailByConsecutive {
    public static void main(String[] args) throws IOException
    {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        // kafka数据源
        DataStream<EventPO> eventStream = KafkaUtil.read(args, env);
        // 生成KeyedStream
        eventStream.keyBy(new KeySelector<EventPO, Integer>() {
            @Override
            public Integer getKey(EventPO eventPO) throws Exception {
                return eventPO.getUserId();
            }
        });
        Pattern<EventPO, EventPO> pattern = Pattern.<EventPO>begin("login_fail_first")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.LOGIN_FAIL.equals(eventPO.getEventName());
                    }
                })
                /**
                 * 1、个体模式的循环模式 匹配的是 宽松近邻（允许插入其他事件）
                 * 2、consecutive() 匹配模式是 严格近邻（不允许插入其他事件）
                 */
                .times(3)
                .consecutive().within(Time.seconds(60));
    }
}
